import Toast from '../../wxcomponents/vant/toast/toast';
import md5 from 'js-md5';
import CryptoJS from 'crypto-js'
import {mapState} from 'vuex'
export default {
	data () {
		return {
			urlList: [],
		}
	},
	computed: {
		...mapState(['timestampDiff', 'TOKEN', 'Language'])
	},
	methods: {
		http(url, data) {
			return new Promise((resolve, reject) => {
				// 防二次请求
				if (this.urlList.includes(url)) {
					console.log(Toast)
					Toast('请求过于频繁,请稍后再试')
				} else {
					// header 处理和数据处理
					if (typeof data === 'string') {
					  data = JSON.parse(data)
					}
					if (typeof data === 'object') {
					  let arr = Object.keys(data)
					  if (arr.length > 0) {
						arr = arr.sort(function(string1, string2) {
						  let arrList = []
						  let num = string1.length > string2.length ? string1.length : string2.length
						  for (var i = 0; i < num; i++) {
							var val1 = string1[i] || ''
							var val2 = string2[i] || ''
							if (val1 < val2) {
							  arrList.push(false)
							} else if (val1 > val2) {
							  arrList.push(true)
							}
						  }
						  return arrList[0] ? 1 : -1
						})
					  }
					  let newData = {}
					  for (let i in arr) {
						newData = {...newData, ...{[arr[i]]: data[arr[i]]}}
					  }
					  data = newData
					  for (let i in data) {
						if (typeof data[i] === 'string') {
						  data[i] = data[i].replace(/(^\s*)|(\s*$)/g, '')
						}
					  }
					}
					const requestData = JSON.stringify(data)
					const timestamp = (data && data.timestamp) ? data.timestamp : new Date().getTime() + Number(this.timestampDiff)
					const SIGN = this.TOKEN + '&' + (Boolean(requestData) && requestData !== '{}' ? timestamp + '&' + requestData : timestamp)
					console.log(SIGN)
					let header = {
						'content-type': 'application/json', // 默认值
						'X-Sign': md5(SIGN),
						'X-Timestamp': timestamp,
						'Accept-Language': this.Language === 0 ? 'zh-CN' : 'en-US',
						'X-XSRF-TOKEN': this.TOKEN || ''
					}
					this.urlList.push(url)
					let _this = this
					wx.request({
						url: `${url}`,
						data,
						method: 'POST',
						header,
						success(res) {
							if (res.data.code === 200) {
								resolve(res.data.data)
							} else {
								reject(res.data.msg)
							}
						},
						fail(e) {
							reject('请求失败')
						},
						complete() {
							_this.urlList = _this.urlList.filter(item => {
								return item !== url
							})
						}
					})
				}
			})				
			}
	}
}
